package com.example.core.document;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

public class HtmlDocument {
    protected final Document doc;

    private HtmlDocument(Document doc) {
        this.doc = doc;
    }

    public static HtmlDocument parse(String html) {
        return new HtmlDocument(Jsoup.parse(html));
    }

    public static HtmlDocument url(String url) throws IOException {
        return new HtmlDocument(Jsoup.connect(url).get());
    }

    public Document origin() {
        return doc;
    }

    public List<HtmlElement> xpath(String exp) {
        return doc.selectXpath(exp).stream().map(HtmlElement::of).toList();
    }

    public Optional<HtmlElement> xpath(String exp, int index) {
        List<HtmlElement> elements = xpath(exp);
        if (elements.isEmpty()) {
            return Optional.empty();
        }
        HtmlElement element = elements.get(index);
        return Optional.of(element);
    }
}
